package com.copa.module.user.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.copa.domain.ResponseDto;
import com.copa.module.user.domain.dto.UserAddressDto;
import com.copa.module.user.domain.entity.UserAddressEntity;
import com.copa.module.user.domain.entity.UserEntity;
import com.copa.module.user.domain.vo.UserAddressAddVo;
import com.copa.module.user.domain.vo.UserAddressUpdateVo;
import com.copa.module.user.manage.UserRoleManage;
import com.copa.module.user.mapper.UserAddressDao;
import com.copa.module.user.service.UserAddressService;
import com.google.common.collect.Maps;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * @author copa
 * @createDate 2021-01-14 13:42
 * @function
 */
@Service
public class UserAddressServiceImpl implements UserAddressService {

    @Autowired
    private UserRoleManage userRoleManage;

    @Autowired
    private UserAddressDao userAddressDao;

    @Override
    public ResponseDto<List<UserAddressDto>> list(String openId) {
        ResponseDto<UserEntity> userRes = userRoleManage.getUserByOpenId(openId);
        if (userRes.isNotSuccess()) {
            return ResponseDto.errorMsg(userRes.getMsg());
        }

        List<UserAddressDto> userAddressDtos = userAddressDao.findByUserId(userRes.getData().getId());
        return ResponseDto.success(userAddressDtos);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseDto<String> add(UserAddressAddVo userAddressAddVo, String openId) {
        Long userId = userRoleManage.getUserByOpenId(openId).getData().getId();
        ResponseDto<List<UserAddressDto>> addressListRes = list(openId);
        if (userAddressAddVo.getIsDefault() == 1 && addressListRes.getData().size() > 0) {
            // 若设置了默认地址
            ResponseDto<String> modifyIsDefaultAddressRes = modifyIsDefaultAddress(userId);
            if (modifyIsDefaultAddressRes.isNotSuccess()) {
                return ResponseDto.errorMsg(modifyIsDefaultAddressRes.getMsg());
            }
        }
        Boolean flag = userAddressDao.insertUserAddressAddVo(userAddressAddVo, userId);
        if (!flag) {
            return ResponseDto.errorMsg("系统繁忙，请稍后再试！");
        }
        return ResponseDto.success();
    }

    @Override
    public ResponseDto<UserAddressDto> get(Long addressId, String openId) {
        ResponseDto<UserEntity> userRes = userRoleManage.getUserByOpenId(openId);
        if (userRes.isNotSuccess()) {
            return ResponseDto.errorMsg(userRes.getMsg());
        }

        Map<String, Object> selectConditions = Maps.newHashMap();
        selectConditions.put("user_id", userRes.getData().getId());
        selectConditions.put("id", addressId);
        List<UserAddressEntity> userAddressEntities = userAddressDao.selectByMap(selectConditions);
        if (ObjectUtil.isNull(userAddressEntities)
            || ObjectUtil.length(userAddressEntities) == 0) {
            return ResponseDto.errorMsg("查不到所查的地址！");
        }
        UserAddressDto userAddressDto = new UserAddressDto();
        userAddressDto.setId(addressId);
        BeanUtils.copyProperties(userAddressEntities.get(0), userAddressDto);
        return ResponseDto.success(userAddressDto);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseDto<String> put(UserAddressUpdateVo userAddressUpdateVo, String openId) {
        Long userId = userRoleManage.getUserByOpenId(openId).getData().getId();
        if (userAddressUpdateVo.getIsDefault() == 1) {
            // 若设置了默认地址
            ResponseDto<String> modifyIsDefaultAddressRes = modifyIsDefaultAddress(userId);
            if (modifyIsDefaultAddressRes.isNotSuccess()) {
                return ResponseDto.errorMsg(modifyIsDefaultAddressRes.getMsg());
            }
        }

        UserAddressUpdateVo addressVo = userAddressDao.findByUserIdAndAddressId(userId, userAddressUpdateVo.getAddressId());
        if (ObjectUtil.isNotNull(addressVo)) {
            UserAddressEntity userAddressEntity = new UserAddressEntity();
            BeanUtils.copyProperties(userAddressUpdateVo, userAddressEntity);
            userAddressEntity.setId(userAddressUpdateVo.getAddressId());
            userAddressDao.updateById(userAddressEntity);
            return ResponseDto.success();
        }
        return ResponseDto.errorMsg("修改失败，请稍后再修改！");
    }

    @Override
    public ResponseDto<UserAddressDto> getDefaultAddress(String openId) {
        ResponseDto<UserEntity> userRes = userRoleManage.getUserByOpenId(openId);
        if (userRes.isNotSuccess()) {
            return ResponseDto.errorMsg(userRes.getMsg());
        }
        Long userId = userRes.getData().getId();
        UserAddressDto userAddressDto = userAddressDao.findDefaultAddress(userId, 1);
        if (ObjectUtil.isNotNull(userAddressDto)) {
            return ResponseDto.success(userAddressDto);
        }
        // 没设默认，则拿地址栏第一个代替
        userAddressDto = userAddressDao.findDefaultAddress(userId, null);
        if (ObjectUtil.isNotNull(userAddressDto)) {
            return ResponseDto.success(userAddressDto);
        }
        return ResponseDto.errorMsg("没有查询到该用户的地址！");
    }


    /**
     * 若设置了默认地址，则将此地址设置为默认地址
     * @param userId
     * @return
     */
    private ResponseDto<String> modifyIsDefaultAddress(Long userId) {
        Boolean flag = userAddressDao.updateDefaultAddressByUserId(userId);
        if (flag) {
            return ResponseDto.success();
        }
        return ResponseDto.errorMsg("系统繁忙，请稍后再试！");
    }
}
